﻿<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="KalturaNWeb.Pages.Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html id="inv-kaltura-app-html-<%= this._appPartID %>" xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <link rel="Stylesheet" type="text/css" href="../Resources/CSS/inv-kaltura.css" />
    <script src="../Resources/JS/jquery-1.10.2.js"></script>
    <script src="../Resources/JS/KalturaAPI/kaltura.min.js"></script>
    <script src="../Resources/JS/KalturaAPI/mwEmbedLoader.js"></script>
</head>
<body>
    <form id="invkalturaform" runat="server">
        <div class="inv-kaltura-app" id="inv-kaltura-app-<%= this._appPartID %>">
            <div class="inv-kaltura-filters" id="inv-kaltura-filters-<%= this._appPartID %>">
                <div class="inv-filter-section">
                    <span class="inv-filter-head">PRODUCT TYPE</span>
                    <ul>
                        <li class="inv-filter-link" role="Product Type" data="">Any</li>
                        <li class="inv-filter-link" role="Product Type" data="Power User">Power User</li>
                        <li class="inv-filter-link" role="Product Type" data="End User">End User</li>
                        <li class="inv-filter-link" role="Product Type" data="Expert">Expert</li>
                    </ul>
                </div>
                <div class="inv-filter-section">
                    <span class="inv-filter-head">DEPARTMENT</span>
                    <ul>
                        <li class="inv-filter-link" role="Department" data="">Any</li>
                        <li class="inv-filter-link" role="Department" data="Marketing">Marketing</li>
                        <li class="inv-filter-link" role="Department" data="Sales">Sales</li>
                    </ul>
                </div>
                <div class="inv-filter-section">
                    <span class="inv-filter-head">SHOW ALL VIDEOS</span>
                    <ul>
                        <li class="inv-filter-link" role="History" data="">Any</li>
                        <li class="inv-filter-link" role="History" data="yes">Most Recent</li>
                    </ul>
                </div>
            </div>
            <div id="inv-kaltura-player-<%= this._appPartID %>" class="inv-kaltura-player">
                <span class="inv-player-title">VIDEO</span>
                <span class="inv-player-notify" id="inv-player-notify-<%= this._appPartID %>">Loading...</span>
                <span class="inv-player-error" id="inv-player-error-<%= this._appPartID %>"></span>
                <div id="inv-kaltura-player-object-<%= this._appPartID %>" class="inv-kaltura-player-object" style="display: none"></div>

            </div>
            <div class="inv-kaltura-playlist">
                <span class="inv-playlist-head">VIDEO PLAYLIST</span>
                <span class="inv-playlist-notify" id="inv-playlist-notify-<%= this._appPartID %>">Loading...</span>
                <span class="inv-playlist-error" id="inv-playlist-error-<%= this._appPartID %>"></span>
                <div class="inv-playlist-list">
                    <div id="inv-kaltura-playlist-<%= this._appPartID %>"></div>
                </div>
            </div>
        </div>
    </form>

    <script type="text/javascript">
        // -------- GLOBALS SETTINGS ---------
        var APP_MIN_WIDTH = 872

        $(document).ready(function () {
            
            /* To be collected from user setting  */
            var KalturaVideoEntryId = "0_lmwwv9g6";
            var PARTNER_ID = "102";
            var UIConfigurationId = "11601127";

            var KalturaVideoEntryId = "0_36l18bru";
            var PARTNER_ID = "1471752";
            var UIConfigurationId = "21935942";

            //var kWidgetLoaderPath = "../Resources/JS/KalturaAPI/mwEmbedLoader.js";
            //"https://cdnsecakmi.kaltura.com/html5/html5lib/v2.1.2/mwEmbedLoader.php";
            // http://innvideo.innovation-365.com/index.php/kwidget/wid/_102/uiconf_id/11601127/entry_id/0_tp0t7n5r
            //"https://html5.kaltura.org/js";                                    
            //"http://cdnapi.kaltura.com/p/{PARTNER_ID}/sp/{PARTNER_ID}00/embedIframeJs/uiconf_id/{uiConfId}/partner_id/{PARTNER_ID}
            //"https://cdnsecakmi.kaltura.com/html5/html5lib/v2.1.2/mwEmbedLoader.php/partner_id/1471752/uiconf_id/21935942");

            try {

                setHostParams();

                //create a kaltura session to be used in later api calls
                createSession();

                if (!sessionResult && sessionResult == '' && sessionResult == null) {
                    throw "Unable to create session";
                }
                else {

                    // load after required parameters are received from server
                    if (KalturaVideoEntryId && PARTNER_ID && UIConfigurationId) {
                        $('#inv-player-notify-<%= this._appPartID %>').slideDown("slow");

                        try {
                            //load the kWidget library and then place the player
                            //$.getScript(kWidgetLoaderPath)
                            //.done(function (script, textStatus) {
                            TargetId = "inv-kaltura-player-object-<%= this._appPartID %>";
                            loadPlayer(PARTNER_ID, UIConfigurationId, KalturaVideoEntryId, TargetId);
                            //})
                            //.fail(function (jqxhr, settings, exception) {
                            //    $('#inv-player-notify-<%= this._appPartID %>').slideUp("slow", function () {
                            //        $('#inv-player-error-<%= this._appPartID %>').slideDown("slow");
                            //        $('#inv-player-error-<%= this._appPartID %>').text("Some error occurred : " + e.message);
                            //    });
                            //});                    
                        }
                        catch (e) {
                            $('#inv-player-notify-<%= this._appPartID %>').slideUp("slow", function () {
                                $('#inv-player-error-<%= this._appPartID %>').slideDown("slow");
                                $('#inv-player-error-<%= this._appPartID %>').text("Some error occurred : " + e.message);
                            });
                        }

                        //loadFilterParametersFromURL();
                        loadPlaylist(kalturaProductType, departmentName, showMostRecentVideo);
                        //loadCategories();
                        //loadMetadataProfiles();
                    }
                }
            } catch (e) {
                $('#inv-player-notify-<%= this._appPartID %>').slideUp("slow", function () {
                    $('#inv-player-error-<%= this._appPartID %>').slideDown("slow");
                    $('#inv-player-error-<%= this._appPartID %>').text("Some error occurred : " + e.message);
                });

                $('#inv-player-notify-<%= this._appPartID %>').slideUp("slow", function () {
                    $('#inv-player-error-<%= this._appPartID %>').slideDown("slow");
                    $('#inv-player-error-<%= this._appPartID %>').text("Some error occurred : " + e.message);
                });
            }

            //resizeApp();
        });

        var loadFilterParametersFromURL = function () {

            try {
                //console.log('loading filter parameters ');
                var queryString = window.location.search.split('?')[1];

                //console.log('queryString  : ' + queryString);
                queryString = decodeURIComponent(queryString);
                //console.log('decoded queryString  : ' + queryString);
                var QSparams = queryString.split('&');

                for (var i = 0; i < QSparams.length; ++i) {
                    console.log('qs param  : ' + QSparams[i]);
                    if (QSparams[i].split('=')[0] == 'DepartmentName') {
                        if (QSparams[i].split('=')[1] && QSparams[i].split('=')[1] != '') {
                            departmentName = QSparams[i].split('=')[1];
                        }
                        else {
                            departmentName = '';
                        }
                    }
                    else if (QSparams[i].split('=')[0] == 'ProductType') {
                        if (QSparams[i].split('=')[1] && QSparams[i].split('=')[1] != '') {
                            kalturaProductType = QSparams[i].split('=')[1];
                        }
                        else {
                            kalturaProductType = '';
                        }
                    }
                    else if (QSparams[i].split('=')[0] == 'ShowMostRecentVideo') {
                        if (QSparams[i].split('=')[1] && QSparams[i].split('=')[1] != '') {
                            showMostRecentVideo = QSparams[i].split('=')[1];
                        }
                        else {
                            showMostRecentVideo = '';
                        }
                    }
                }
            } catch (e) {
                //console.log('error in this function');
            }

            //console.log('end for loop');
        }

        var senderId = null;
        var hostUrl = null;
        var setHostParams = function () {
            try {
                if (decodeURIComponent(document.URL).indexOf('?') != -1) {
                    var params = decodeURIComponent(document.URL).split("?")[1].split("&");
                    for (var i = 0; i < params.length; i = i + 1) {
                        var param = params[i].split("=");
                        if (param[0] == 'SPHostUrl') {
                            hostUrl = decodeURIComponent(param[1]);
                        }

                        if (param[0] == 'SenderId') {
                            senderId = decodeURIComponent(param[1]);
                        }
                    }

                    if (hostUrl == null) {
                        hostUrl = '*';
                    }

                    if (senderId == null) {
                        senderId = '*';
                    }
                }
            } catch (e) {
                console.log('error in setHostParams');
            }
        }

        var resizeApp = function () {
            var height = $('#inv-kaltura-app-<%= this._appPartID %>').height();
            var width = $('#inv-kaltura-app-<%= this._appPartID %>').width();

            var htmlHeight = $('#inv-kaltura-app-html-<%= this._appPartID %>').height();
            //var htmlwidth = $('#inv-kaltura-app-html-<%= this._appPartID %>').width();

            if (window.parent == null)
                return;


            //use postmessage to resize the app part. 
            //target.postMessage('<message senderId=' + results[1] + '>resize(100% ,' + (apQuery("html").height()) + ')</message>', '*');
            var message = '<Message senderId=' + senderId + '>' +
                              'resize(100%,' + htmlHeight + ')' +
                          '</Message>';

            //console.log('Message sending # sender id :' + senderId + '  hostUrl : ' + hostUrl);
            //console.log(height + '   ' + width);
            //console.log(htmlheight + '   ' + htmlwidth);
            //window.parent.postMessage(message, hostUrl);
            //console.log('message sent ');
        }

        var adjustPlayerSize = function () {
            //adjust player size
            var playerWidth = $('#inv-kaltura-player-<%= this._appPartID %>').width();
            var playerHeight = playerWidth * 0.9;
            $('#inv-kaltura-player-<%= this._appPartID %>').find('object').css({ "width": playerWidth, "height": playerHeight });
        }

        var adjustPlaylistSize = function () {
            //adjust player size
            var playerHeight = $('#inv-kaltura-player-<%= this._appPartID %>').find('object').height();
            $('#inv-kaltura-playlist-<%= this._appPartID %>').parent().parent().css({ "height": playerHeight + 35 });
            $('#inv-kaltura-playlist-<%= this._appPartID %>').parent().css({ "height": playerHeight - 6 });
        }

        var adjustFilterSize = function () {
            //adjust player size
            var playerHeight = $('#inv-kaltura-player-<%= this._appPartID %>').find('object').height();
            $('#inv-kaltura-filters-<%= this._appPartID %>').css({ "height": playerHeight + 31 });
        }


        $(window).resize(function () {
            if ($('#inv-kaltura-app-<%= this._appPartID %>').width() > 872) {
                adjustPlayerSize();
                adjustPlaylistSize();
                adjustFilterSize();
            }
        });
        

        $(".inv-filter-link").click(function () {
            //change color scheme of current selection
            var selected = $(this);
            $('.inv-filter-link').removeClass('active-filter');
            $(this).addClass('active-filter');

            var filter = $(this).attr('role');

            if (filter == 'Product Type') {
                kalturaProductType = $(this).attr('data');
            }
            else if (filter == 'Department') {
                departmentName = $(this).attr('data');
            }
            else if (filter == 'History') {
                showMostRecentVideo = $(this).attr('data');
            }

            

            <%--
            // to reload the page and rebuild querystring, unhide this part
            if (filter == 'History') {
                showMostRecentVideo = $(this).attr('data');
                //fade out existing playlist
                $($('#inv-kaltura-playlist-<%= this._appPartID %>').find("div")).fadeOut("slow");

                //hide errors
                $('#inv-playlist-error-<%= this._appPartID %>').slideUp("fast");
                $('#inv-playlist-error-<%= this._appPartID %>').text('');

                // display loading notification
                $('#inv-playlist-notify-<%= this._appPartID %>').slideDown("slow");

                loadPlaylist(kalturaProductType, departmentName, showMostRecentVideo);
            }
            else {
                RefreshParentWindow($(this));
            }
            --%>



            //fade out existing playlist
            $($('#inv-kaltura-playlist-<%= this._appPartID %>').find("div")).fadeOut("slow");

            //hide errors
            $('#inv-playlist-error-<%= this._appPartID %>').slideUp("fast");
            $('#inv-playlist-error-<%= this._appPartID %>').text('');

            // display loading notification
            $('#inv-playlist-notify-<%= this._appPartID %>').slideDown("slow");

            loadPlaylist(kalturaProductType, departmentName, showMostRecentVideo);
        });

        var loadPlayer = function (PartnerId, UIConfigurationId, KalturaVideoEntryId, TargetId) {
            //embed the player in the target place            

            kWidget.embed({
                targetId: TargetId,
                wid: '_' + PARTNER_ID,
                uiconf_id: UIConfigurationId,
                entry_id: KalturaVideoEntryId,
                readyCallback: function () {
                    adjustPlayerSize();
                    adjustPlaylistSize();
                    adjustFilterSize();

                    //hide loading notification
                    $('#inv-player-notify-<%= this._appPartID %>').slideUp("slow");
                },
                flashvars: {
                    "userAgentPlayerRules": {
                        "includeInLayout": false,
                        "loadingPolicy": "onDemand",
                        "disableForceMobileHTML5": false,
                        "r1RegMatch": "/Chrome/(1[5-9]|[1-9][0-9]+)/",
                        "r1LeadWithHTML5": true,
                        "r2Match": "Firefox/3.6",
                        "r2ForceFlash": false,
                        "r3Match": "iPhone",
                        "r3ForceMsg": "%3Ch3%3ESorry%3C/h3%3E%20Your%20device%20is%20%3Cb%3Enot%20supported%3Cb%3E",
                        "r4RegMatch": "/Firefox/([4-9]|[0-9][0-9])/",
                        "r4LeadWithHTML5": true
                    }
                }
            });
        }

        jQuery.support.cors = true;

        var SECRET = "91d4eafa83dca18e4eca98e062f6d70c";
        var USER_ID = "sbastos01@gmail.com";
        var PARTNER_ID = 1471752;
        var METADATA_ID = 2537172;
        var KALTURA_SERVICE_URL = "https://www.kaltura.com/";

        //var SECRET = "38ce28c09f89add18e5e6ca43bc17ac1";
        //var USER_ID = "sbastos@innovation-365.com";
        //var PARTNER_ID = 102;
        //var METADATA_ID = 3;
        //var KALTURA_SERVICE_URL = "https://innvideo.innovation-365.com";

        var config = new KalturaConfiguration(PARTNER_ID);
        config.serviceUrl = KALTURA_SERVICE_URL;
        var client = new KalturaClient(config);
        var type = KalturaSessionType.ADMIN;
        var kalturaResponseType = KalturaResponseType.RESPONSE_TYPE_XML;
        var expiry = null;
        var privileges = null;
        var profileId = METADATA_ID; //ID of Custom metadata for ProductType 
        var sessionResult = null;

        var kalturaProductType = "";
        var departmentName = "";
        var showMostRecentVideo = "";

        var createSession = function () {
            client.session.start(function (success, results) {
                sessionResult = results;
            }, SECRET, USER_ID, type, PARTNER_ID, expiry, privileges);
        }

        var loadPlaylist = function (kalturaProductType, departmentName, showMostRecentVideo) {
            // start Kaltura Session  

            var result = client.session.start(function (success, results) { cbSessionStart(success, results, profileId, kalturaProductType, departmentName, showMostRecentVideo); }, SECRET, USER_ID, type, PARTNER_ID, expiry, privileges);
        }

        var loadMetadataProfiles = function () {
            var result = client.session.start(function (success, results) {
                client.metadataProfile.listAction(function (success, results) {
                    $.each(results.objects, function () {
                        var metadataProfile = $(this)[0];

                        var filter = new KalturaMetadataFilter();
                        filter.metadataProfileIdEqual = null;
                        filter.objectIdEqual = metadataProfile.id;
                        var pager = null;

                        if (metadataProfile.id == 2537172) {
                            client.metadata.listAction(function (success, result) {

                            }, filter, pager);
                        }
                    });
                });
            }, SECRET, USER_ID, type, PARTNER_ID, expiry, privileges);
        }

        var loadCategories = function () {
            var result = client.session.start(function (success, results) {
                client.category.listAction(function (success, results) {

                    $.each(results.objects, function () {
                        var filterCategory = $(this)[0];
                        var filterCategoryMarkup = '<div class="inv-filter-category-step" filter-id="' + filterCategory.id + '" filter-path="' + filterCategory.fullName + '">' + filterCategory.name + '</div>';

                        // only if there are entries under this filter category, append to its parent                    
                        if (filterCategory.entriesCount > 0) {

                            // if top level filter
                            if (filterCategory.depth == 0 || filterCategory.parentId == 0) {
                                $('#inv-kaltura-filters-<%= this._appPartID %>').append(filterCategoryMarkup);
                        }
                                // if sub-filter
                        else {
                            $('div[filter-id="' + filterCategory.parentId + '"]').append(filterCategoryMarkup);
                        }
                    }
                    });
                });
            }, SECRET, USER_ID, type, PARTNER_ID, expiry, privileges);
        }



    var cbSessionStart = function (success, results, profileId, kalturaProductType, departmentName, showMostRecentVideo) {

        try {
            if (!success) {
                //alert(results);
            }

            if (results == undefined) {
                throw "Unable to read data";
            }

            if (results.code && results.message) {
                throw "Error in data";
                //alert(results.message);
                //return;
            }

            if (success) {
                //start session with Kaltura
                client.setKs(results);
                //set KS to text field for saving on the page
                //
                var filter = new KalturaMediaEntryFilter();
                //filter.
                filter.orderBy = KalturaBaseEntryOrderBy.RECENT_DESC;

                // create advanced search object
                var filterAdvancedSearch = new KalturaMetadataSearchItem();

                // assign profile id
                filterAdvancedSearch.metadataProfileId = profileId; // Obtained by calling metadataProfile service and getting the profile ID

                // type of the search (AND or OR)
                //filterAdvancedSearch.type = KalturaSearchOperatorType.SEARCH_AND;
                filterAdvancedSearch.type = KalturaSearchOperatorType.SEARCH_OR;

                // object type is essential because of a bug in js client library
                filterAdvancedSearch.objectType = 'KalturaMetadataSearchItem';

                // now we define the search condition
                var filterAdvancedSearchItem = new KalturaSearchCondition();
                // define the field we are searching with xpath
                filterAdvancedSearchItem.field = "/*[local-name()='metadata']/*[local-name()='ProductType']"; // Replace name with the name obtained by calling metadataProfile service and showing defined fields
                filterAdvancedSearchItem.value = kalturaProductType; // assign value
                // object type is essential because of a bug in js client library
                filterAdvancedSearchItem.objectType = 'KalturaSearchCondition';

                filterAdvancedSearch.items = [filterAdvancedSearchItem];

                // assign advanced search object back to the filter
                if (kalturaProductType != "") {
                    filter.advancedSearch = filterAdvancedSearch;
                }
                if (departmentName != "") {
                    filter.categoriesMatchOr = "SharePoint>" + departmentName;
                }


                var pager = new KalturaFilterPager();
                pager.pageSize = 10; //Sets the number of returned items
                if (showMostRecentVideo == "yes") {
                    filter.advancedSearch = null;
                    filter.categoriesMatchOr = "";
                    //filter.orderBy = '-recent';
                    pager.pageSize = 1;
                }
                pager.pageIndex = 1;
                var result1 = client.media.listAction(function (success, results) { cbEntriesList(success, results); }, filter, pager);
            }
        }
        catch (e) {
            $('#inv-playlist-notify-<%= this._appPartID %>').slideUp("slow", function () {
                $('#inv-playlist-error-<%= this._appPartID %>').slideDown("slow");
                $('#inv-playlist-error-<%= this._appPartID %>').text("Some error occurred : " + e);
            });
        }
    };

    var cbEntriesList = function (success, results) {
        try {
            if (!success) {
                //alert(results);
            }

            if (results == undefined) {
                throw "Unable to read data";
            }

            if (results.code && results.message) {
                //alert(results.message);
                //return;
            }
            if (success) {
                //displayEntriesTable(results);
                displayVideoInformation(results);
            }
        }
        catch (e) {
            $('#inv-playlist-notify-<%= this._appPartID %>').slideUp("slow", function () {
                $('#inv-playlist-error-<%= this._appPartID %>').slideDown("slow");
                $('#inv-playlist-error-<%= this._appPartID %>').text("Some error occurred : " + e);
            });
        }
    };

    var displayVideoInformation = function (videoMetadataInfo) {
        kalturaObjectsArrayCounter = 0;
        jQuery.support.cors = true;
        var videoId = 0;
        try {
            kalturaObjectIdsArray = new Array(videoMetadataInfo.objects.length);
            var tempCntr = 0;
            var htmlStructure = '';
            //alert(videoMetadataInfo.objects.length);
            if (videoMetadataInfo.objects.length > 0) {
                $.each(videoMetadataInfo.objects, function () {
                    htmlStructure = "<div class='inv-entry-thumbnail' id='tblThumbnail" + $(this)[0].id + "'>"
                                                  + "<img alt='thumbnail' class='inv-entry-image' src='" + $(this)[0].thumbnailUrl + "' />"
                                                  + "<div class='inv-entry-metadata' id='tbl" + $(this)[0].id + "'>"
                                                  + "<a class='cs-title' data-entryId='" + $(this)[0].id + "' href='KalturaVideo-WithAPI_1.aspx' onclick='javascript:return videoLinkClicked(this,\"" + $(this)[0].id + "\");'>" + $(this)[0].name + "</a>"
                                                  //+ "<label>Description</label>:<span>" + $(this)[0].description + "</span>"
                                                  + "<div class='tags'><label>Tags</label>:<span>" + (($(this)[0].tags == null) ? '' : $(this)[0].tags) + "</span></div>"
                                                  + "<div class='categories'><label>Categories</label>:<span>" + (($(this)[0].categories == null) ? '' : $(this)[0].categories) + "</span></div>";

                    kalturaObjectIdsArray[tempCntr] = $(this)[0].id;
                    //alert(kalturaObjectIdsArray[tempCntr]);
                    tempCntr++;
                    htmlStructure = htmlStructure + "</div></div>";
                    $("#inv-kaltura-playlist-<%= this._appPartID %>").append(htmlStructure);

                    var customMetaDataFilter = new KalturaMetadataFilter();
                    customMetaDataFilter.advancedSearch = new KalturaMetadataSearchItem();
                    customMetaDataFilter.objectIdEqual = $(this)[0].id;
                    var customMetaDataPager = new KalturaFilterPager();
                    customMetaDataPager.pageSize = 1;
                    customMetaDataPager.pageIndex = 1;

                    //resizeApp();
                    var result22 = client.metadata.listAction(function (success, results) { cbCustomMetadataFields(success, results); }, customMetaDataFilter, customMetaDataPager);
                });
            }
            else {
                $('#inv-playlist-notify-<%= this._appPartID %>').slideUp("slow");
            }
        }
        catch (e) {
            $('#inv-playlist-notify-<%= this._appPartID %>').slideUp("slow", function () {
                $('#inv-playlist-error-<%= this._appPartID %>').slideDown("slow");
                $('#inv-playlist-error-<%= this._appPartID %>').text("Some error occurred : " + e.message);
            });
        }
    };

    var cbCustomMetadataFields = function (success, results) {
        if (!success) {
            alert(results);
        }
        if (results.code && results.message) {
            alert(results.message);
            return;
        }
        if (success) {
            processGetCustomVideoMetaData(results);
        }
    };

    var processGetCustomVideoMetaData = function (jsonCustomVideoMetaData) {
        var customMetadata = "";
        var ptCnt = 0;
        $.each(jsonCustomVideoMetaData.objects, function () {
            var xmlV = $.parseXML($(this)[0].xml);

            $(xmlV).find("metadata").find("DeptName").each(function () {

                customMetadata = customMetadata + "<div class='department'><label>Department Name</label>:<span>" + $(this).text() + "</span></div>";

            });

            if ($(xmlV).find("metadata").find("ProductType").text() != "" && $(xmlV).find("metadata").find("ProductType").text() != "undefined") {
                customMetadata = customMetadata + "<div class='type'>";
                $(xmlV).find("metadata").find("ProductType").each(function () {
                    if (ptCnt == 0) {
                        customMetadata = customMetadata + "<label >Product Type</label>:";
                        ptCnt++;
                    }

                    customMetadata = customMetadata + "<span>" + $(this).text() + "</span>,";
                });

                customMetadata = customMetadata + "</div>";
            };

            // bind custom metadata structure with respective Video item
            customMetadata = customMetadata + "";
            var tableToBindWith = "#tbl" + $(this)[0].objectId;

            $(tableToBindWith).append(customMetadata);
            kalturaObjectsArrayCounter++;
        });

        // display loading notification
        $('#inv-playlist-notify-<%= this._appPartID %>').slideUp("slow");

        resizeApp();
    }

    var videoLinkClicked = function (linkControlObject, idOfVideo) {
        $('#inv-player-notify-<%= this._appPartID %>').slideDown("slow");

        kWidget.addReadyCallback(function () {
            var kdp = document.getElementById("inv-kaltura-player-object-<%= this._appPartID %>");
            kdp.sendNotification("changeMedia", { 'entryId': idOfVideo });
            //kdp.sendNotification( "doPlay");
            //kdp.sendNotification("doSeek", 0); 
            //kdp.setKDPAttribute("mediaProxy", "mediaPlayFrom", 0);
            kdp.kBind('mediaReady', function () {
                kdp.sendNotification('doPlay');
                //$('#inv-player-notify-<%= this._appPartID %>').slideUp("slow");
            })

            $('#inv-player-notify-<%= this._appPartID %>').slideUp("slow");
        });
        return false;
    }


    </script>

    <script>
        function RefreshParentWindow(source) {

            var params = '';
            var filter = source.attr('role');

            if (filter == 'Product Type') {
                var parameterValue = source.attr('data');
                if (parameterValue == '') {
                    parameterValue = 'Any';
                }
                params = 'appParams:ProductType=' + parameterValue;
            }
            else if (filter == 'Department') {
                var parameterValue = source.attr('data');
                if (parameterValue == '') {
                    parameterValue = 'Any';
                }
                params = 'appParams:DepartmentName=' + parameterValue;
            }

            console.log('posing message : ' + params);
            window.parent.postMessage(params, '*');
        }
     
    </script>
</body>
</html>
